package com.order.controller;

import com.order.common.PageQuery;
import com.order.common.Result;
import com.order.dto.CreateOrderRequest;
import com.order.entity.OrderInfo;
import com.order.service.OrderService;
import com.order.util.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 分页查询订单列表
     */
    @GetMapping("/list")
    public Result<List<OrderInfo>> getOrderList(
            PageQuery pageQuery,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            List<OrderInfo> orders = orderService.getOrderList(pageQuery, status, categoryId, userId, roleType);
            Long total = orderService.countOrders(pageQuery, status, categoryId, userId, roleType);
            
            return Result.success(orders, total);
        } catch (Exception e) {
            return Result.error("查询订单列表失败");
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result<OrderInfo> getOrderDetail(@PathVariable Long id) {
        try {
            OrderInfo order = orderService.getOrderById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("获取订单详情失败");
        }
    }

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<String> createOrder(
            @Valid @RequestBody CreateOrderRequest request,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有用户可以创建订单
            if (roleType != 3) {
                return Result.forbidden("只有用户可以发布需求");
            }
            
            orderService.createOrder(request, userId);
            return Result.success("订单创建成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 技术员接单
     */
    @PostMapping("/{id}/accept")
    public Result<String> acceptOrder(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有技术员可以接单
            if (roleType != 4) {
                return Result.forbidden("只有技术员可以接单");
            }
            
            orderService.acceptOrder(id, userId);
            return Result.success("接单成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 派单员指派订单
     */
    @PostMapping("/{id}/assign")
    public Result<String> assignOrder(
            @PathVariable Long id,
            @RequestBody Map<String, Long> request,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long dispatcherId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有派单员可以指派订单
            if (roleType != 2) {
                return Result.forbidden("只有派单员可以指派订单");
            }
            
            Long techId = request.get("techId");
            if (techId == null) {
                return Result.badRequest("请选择技术员");
            }
            
            orderService.assignOrder(id, techId, dispatcherId);
            return Result.success("指派成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 完成订单
     */
    @PostMapping("/{id}/complete")
    public Result<String> completeOrder(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            orderService.completeOrder(id, userId, roleType);
            return Result.success("订单完成");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public Result<String> cancelOrder(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            orderService.cancelOrder(id, userId, roleType);
            return Result.success("订单已取消");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}